package org.facyt.commons.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;

import javax.servlet.http.HttpSession;

import org.facyt.commons.view.interfaces.window.WindowInfo;
import org.facyt.commons.view.interfaces.window.WindowMessage;
import org.facyt.vacas.FacytApplication;
import org.facyt.vacas.util.ConstantesWeb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;

import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.WebApplicationContext;

public class VaadinUtil {

	protected static final Logger logger = LoggerFactory
			.getLogger(VaadinUtil.class);

	public static Application application;
	
	private static MessageSource messageSource;
	
	public static void setMessageSource(MessageSource messageSource) {
		VaadinUtil.messageSource = messageSource;
	}
	
	/**
	 * Obtiene las propiedades
	 * 
	 * @param key
	 * @param parametros
	 * @return
	 */
	public static String getProperties(String key, Object... parameters) {
		return messageSource.getMessage(key, parameters, null);
	}

	/**
	 * Recupera la sessión actual de la aplicación
	 * 
	 * @param component
	 * @return
	 */
	public static HttpSession getSession() {
		WebApplicationContext webApplicationContext = (WebApplicationContext) ((FacytApplication)application).getContext();
		return webApplicationContext.getHttpSession();
	}
	
	/**
	 * Muestra el error en una pantalla
	 * @param keyMessage
	 */
	public static void showMessageError(String keyMessage){
		showMessageError(keyMessage, null);
	}

	/**
	 * Muestra el error en una pantalla
	 * @param keyMessage
	 * @param exception
	 */
	public static void showMessageError(
			String keyMessage, Throwable exception) {
		WindowInfo info = null;
		if (exception != null) {
			StringWriter sw = null;
			PrintWriter pw = null;
			try{
				sw = new StringWriter();
				pw = new PrintWriter(sw);
				exception.printStackTrace(pw);

				info = new WindowInfo(application,
						VaadinUtil.getProperties(keyMessage), sw.toString(),
						ConstantesWeb.Icons.ICON_ERROR);
			} finally {
				if (sw != null) {
					try {
						sw.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (pw != null) {
					try {
						pw.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			

		} else {
			info = new WindowInfo(application,
					VaadinUtil.getProperties(keyMessage),
					 ConstantesWeb.Icons.ICON_ERROR);
		}
		WindowMessage.createWindowMessage(info);
	}
}
